import os
import re
import chardet


def read_file(filepath):
    with open(filepath, 'rb') as f:
        encoding = chardet.detect(f.read()) [ 'encoding' ]
        return encoding


def modify_file_content(file_path, regex, new_content):
    file_encoding = read_file(file_path)
    with open(file_path, 'r', encoding=file_encoding) as f:
        content = f.read()
        print(1111, content)
    new_content = re.sub(regex, new_content, content)
    print(2222, new_content)
    tmp_file = os.path.join(os.path.dirname(file_path), 'tmp.txt')
    with open(tmp_file, 'w', encoding='utf-8') as f:
        f.write(new_content)
    os.replace(tmp_file, file_path)
